<template>
  <el-dialog
    :title="!dataForm.freightId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @submit.native.prevent="dataFormSubmit()" label-width="80px">
    <el-form-item label="名称" prop="freightTitle">
      <el-input v-model="dataForm.freightTitle" placeholder="运费模板名称"></el-input>
    </el-form-item>
    <el-form-item label="类型" prop="chargingType">
      <el-radio v-model="dataForm.chargingType" label= 0>计件</el-radio>
      <el-radio v-model="dataForm.chargingType" label= 1>计重</el-radio>
      <!-- <el-input v-model="dataForm.chargingType" placeholder="计费类型（0：计件；1：计重）"></el-input> -->
    </el-form-item>
    <el-form-item label="首费" prop="firstChargeNum">
      <el-row>
        <el-col>
          <el-input v-model="dataForm.firstChargeNum" placeholder="件数/重量" style="width: 100px"/><span style="font-size:16px">{{this.dataForm.chargingType === '0' ? '件内' : 'kg内'}}</span><el-input v-model="dataForm.firstCharge" placeholder="首费金额" style="width: 100px"/><span style="font-size:16px">元</span>
        </el-col>
      </el-row>
      <!-- <el-input v-model="dataForm.firstChargeNum" placeholder="首费件数/首费重量"></el-input> -->
    </el-form-item>
    <el-form-item label="续费" prop="renew">
      <el-row>
        <el-col>
          <el-input v-model="dataForm.renewNum" placeholder="件数/重量" style="width: 100px"/><span style="font-size:16px">{{this.dataForm.chargingType === '0' ? '件内' : 'kg内'}}</span><el-input v-model="dataForm.renew" placeholder="首费金额" style="width: 100px"/><span style="font-size:16px">元</span>
        </el-col>
      </el-row>
      <!-- <el-input v-model="dataForm.renew" placeholder="续费（首费上追加）"></el-input> -->
    </el-form-item>
    <el-form-item label="特殊地区" prop="specialArea">
      <el-radio v-model="dataForm.specialArea" label= 0>无</el-radio>
      <el-radio v-model="dataForm.specialArea" label= 1>有</el-radio>
      <!-- <el-input v-model="dataForm.specialArea" placeholder="特殊地区（0：无；1：有）"></el-input> -->
    </el-form-item>
    <el-form-item label="选择地区" prop="cityId" v-if="this.dataForm.specialArea === '1'">
      <el-row>
          <el-col>
            <el-select v-model="dataForm.provinceId" placeholder="请选择省" @change="provinceChanged">
              <el-option 
                v-for="item in dataForm.provinceList"
                :key="item.id"
                :label="item.areaName"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="dataForm.cityId" placeholder="请选择市">
              <el-option 
                v-for="item in dataForm.cityList"
                :key="item.id"
                :label="item.areaName"
                :value="item.id">
              </el-option>
            </el-select>
            <el-button type="primary" round @click="addAddress()">添加</el-button>
          </el-col>
        </el-row>
    </el-form-item>
    <el-form-item label="地区列表" prop="dataForm.cityId" v-if="this.dataForm.specialArea === '1' && this.dataForm.specialAreaJson.length > 0">
      <el-table
        class="specs-table"
        :border="true"
        :data="dataForm.specialAreaJson">
        <!-- <el-table-column
          prop="provinceId"
          label="省"
          header-align="center"
          align="left">
          <template slot-scope="scope">
            <el-form-item :prop="`specialAreaJson.${scope.$index}.provinceId`">
              <el-row>
                <el-col>
                  <el-select v-model="scope.row.provinceId" placeholder="请选择省" @change="provinceChanged">
                    <el-option 
                      v-for="item in dataForm.provinceList"
                      :key="item.id"
                      :label="item.areaName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
        </template>
      </el-table-column> -->
        <el-table-column
          prop="cityId"
          label="地区"
          header-align="center"
          align="left"
          v-if="this.old">
          <template slot-scope="scope">
            <el-form-item >
              <el-row>
                <el-col>
                  <el-select v-model="scope.row.provinceId" placeholder="请选择省" @change="provinceChanged">
                    <el-option 
                      v-for="item in dataForm.provinceList"
                      :key="item.id"
                      :label="item.areaName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                  <el-select v-model="scope.row.cityId" placeholder="请选择市" v-if="scope.row.cityId !== ''">
                    <el-option 
                      v-for="item in dataForm.address"
                      :key="item.id"
                      :label="dataForm.address[scope.$index].areaName"
                      :value="scope.row.cityId">
                    </el-option>
                  </el-select>
                  <el-select v-model="scope.row.cityId" placeholder="请选择市" v-if="scope.row.cityId === ''">
                    <el-option 
                      v-for="item in dataForm.address"
                      :key="item.id"
                      label=""
                      :value="scope.row.cityId">
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
        </template>
      </el-table-column>
      <el-table-column
          prop="cityId"
          label="地区"
          header-align="center"
          align="left"
          v-if="!this.old">
          <template slot-scope="scope">
            <el-form-item >
              <el-row>
                <el-col>
                  <el-select v-model="scope.row.provinceId" placeholder="请选择省" @change="provinceChanged">
                    <el-option 
                      v-for="item in dataForm.provinceList"
                      :key="item.id"
                      :label="item.areaName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                  <el-select v-model="scope.row.cityId" placeholder="请选择市">
                    <el-option 
                      v-for="item in dataForm.cityList"
                      :key="item.id"
                      :label="item.areaName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
        </template>
      </el-table-column>
        <el-table-column
          prop="firstChargeNum"
          label="首费数量"
          header-align="center"
          align="center"
          width="80px">
          <template slot-scope="scope">
            <el-form-item :prop="`specialAreaJson.${scope.$index}.firstChargeNum`">
              <el-input v-model="scope.row.firstChargeNum" placeholder="" size="mini" :rules='rules.money'></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          prop="firstCharge"
          label="首费金额"
          header-align="center"
          align="center"
          width="80px">
          <template slot-scope="scope">
            <el-form-item :prop="`specialAreaJson.${scope.$index}.firstCharge`">
              <el-input v-model="scope.row.firstCharge" placeholder="" size="mini" :rules='rules.num'></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          prop="renewNum"
          label="续费数量"
          header-align="center"
          align="center"
          width="80px">
          <template slot-scope="scope">
            <el-form-item :prop="`specialAreaJson.${scope.$index}.renewNum`">
              <el-input v-model="scope.row.renewNum" placeholder="" size="mini" :rules='rules.num'></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          prop="renew"
          label="续费金额"
          header-align="center"
          align="center"
          width="80px">
          <template slot-scope="scope">
            <el-form-item :prop="`specialAreaJson.${scope.$index}.renew`">
              <el-input v-model="scope.row.renew" placeholder="" size="mini" :rules='rules.money'></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          label="操作"
          width="80px">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="deleteHandle(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item label="备注" prop="remarks">
      <el-input type="textarea" v-model="dataForm.remarks" placeholder="备注"></el-input>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data: function() {
      var checkDecimal = (rule, value, callback) => {
        console.log(value)
        if (typeof value === 'object' || value === undefined) {
          value = rule.field
        }
        debugger
        // let reg = /^(^[0-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,}$)$/
        let reg = /^[0-9]\d*$/
        if (Number.parseFloat(value) < 0 || !reg.test(value) || !Number.isFinite(Number.parseFloat(value))) {
          // callback(new Error('数据不合法'))
          callback(this.$message.error('金额不规范！'))
        } else {
          callback()
        }
      }
      var checkInteger = (rule, value, callback) => {
        if (typeof value === 'object' || value === undefined) {
          value = rule.field
        }
        let reg = /^[1-9]\d*$/
        if (Number.parseFloat(value) <= 0 || !reg.test(value)) {
          callback(this.$message.error('数量必须为非零正整数！'))
        } else {
          callback()
        }
      }
      return {
        visible: false,
        old: true,
        dataForm: {
          freightId: 0,
          freightTitle: '',
          chargingType: '0',
          firstChargeNum: '',
          firstCharge: '',
          renew: '',
          isRenew: '',
          renewNum: '',
          specialArea: '0',
          specialAreaJson: [],
          isEnable: '',
          remarks: '',
          createTime: '',
          createUserId: '',
          updateTime: '',
          updateUserId: '',
          state: '',
          provinceList: [],
          cityList:[],
          provinceId: '',
          cityId: '',
          address: []
        },
        rules: {
          price: [
            { validator: checkDecimal, required: true, trigger: 'blur' }
          ],
          num: [
            { validator: checkInteger, required: true, trigger: 'blur' }
          ]
        },
        dataRule: {
          freightTitle: [
            { required: true, message: '运费模板名称不能为空', trigger: 'blur' }
          ],
          chargingType: [
            { required: true, message: '计费类不能为空', trigger: 'blur' }
          ],
          firstChargeNum: [
            { validator: checkInteger, required: true, trigger: 'blur' }
          ],
          firstCharge: [
            { validator: checkDecimal, required: true, trigger: 'blur' }
          ],
          renew: [
            { validator: checkDecimal, required: true, trigger: 'blur' }
          ],
          renewNum: [
            { validator: checkInteger, required: true, trigger: 'blur' }
          ],
          specialArea: [
            { required: true, message: '特殊地区不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.freightTitle = ''
        this.dataForm.chargingType = '0'
        this.dataForm.firstChargeNum = ''
        this.dataForm.firstCharge = ''
        this.dataForm.renew = ''
        this.dataForm.isRenew = ''
        this.dataForm.renewNum = ''
        this.dataForm.specialArea = '0'
        this.dataForm.specialAreaJson = []
        this.dataForm.isEnable = ''
        this.dataForm.remarks = ''
        this.dataForm.createTime = ''
        this.dataForm.createUserId = ''
        this.dataForm.updateTime = ''
        this.dataForm.updateUserId = ''
        this.dataForm.state = ''
        this.dataForm.provinceList = []
        this.dataForm.cityList = []
        this.dataForm.provinceId = ''
        this.dataForm.cityId = ''
        this.dataForm.address = []
        // 初始省
        this.$http({
          url: this.$http.adornUrl('/member/area/queryProvinceList'),
          method: 'post'
        }).then(({data}) => {
          this.dataForm.provinceList = data.data
        })
        debugger
        this.dataForm.freightId = id || 0
        this.visible = true
        // this.$nextTick(() => {
        //   this.$refs['dataForm'].resetFields()
          if (this.dataForm.freightId) {
            this.$http({
              url: this.$http.adornUrl(`/freight/getFreightDetailsInfoId/${this.dataForm.freightId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.freightTitle = data.data.freightTitle
                this.dataForm.chargingType = data.data.chargingType + ''
                this.dataForm.firstChargeNum = data.data.firstChargeNum
                this.dataForm.firstCharge = data.data.firstCharge
                this.dataForm.renew = data.data.renew
                this.dataForm.isRenew = data.data.isRenew
                this.dataForm.renewNum = data.data.renewNum
                this.dataForm.specialArea = data.data.specialArea
                this.dataForm.specialAreaJson = JSON.parse(data.data.specialAreaJson)
                console.log(this.dataForm.specialAreaJson)
                this.dataForm.remarks = data.data.remarks
                debugger
                if (this.dataForm.specialArea === '1') {
                  // for (var i = 0; i < this.dataForm.specialAreaJson.length; i++) {
                  //   console.log(this.dataForm.specialAreaJson[i].cityId)
                  //   this.$http({
                  //     url: this.$http.adornUrl(`/member/area/getAddressDetailsById/${this.dataForm.specialAreaJson[i].cityId}`),
                  //     method: 'get',
                  //     params: this.$http.adornParams()
                  //   }).then(({data}) => {
                  //     console.log(data)
                  //     this.dataForm.address.push(data.data)
                  //     console.log(this.dataForm.address)
                  //   })
                  // }
                  this.$http({
                    url: this.$http.adornUrl(`/member/area/getAddressDetailsById/${this.dataForm.freightId}`),
                    method: 'get',
                    params: this.$http.adornParams()
                  }).then(({data}) => {
                    this.dataForm.address = data.data
                    console.log(this.dataForm.address)
                  })
                }
              }
            })
          }
        // })
      },
      // 表单提交
      dataFormSubmit () {
        if (this.dataForm.specialAreaJson.length <= 0) {
          this.dataForm.specialArea = 0 + ''
        } else {
          this.dataForm.specialArea = 1 + ''
          for (var i = 0; i < this.dataForm.specialAreaJson.length; i++) {
            let res = /^[1-9]\d*$/
            if (Number(this.dataForm.specialAreaJson[i].firstChargeNum) <= 0 || !res.test(this.dataForm.specialAreaJson[i].firstChargeNum)) {
              this.$message.error('特殊地区首费数量不规范！')
              return
            }
            if (Number(this.dataForm.specialAreaJson[i].renewNum) <= 0 || !res.test(this.dataForm.specialAreaJson[i].renewNum)) {
              this.$message.error('特殊地区续费数量不规范！')
              return
            }
            let reg = /^[0-9]\d*$/
            if (Number.parseFloat(this.dataForm.specialAreaJson[i].renew) < 0 || !reg.test(this.dataForm.specialAreaJson[i].renew) || !Number.isFinite(Number.parseFloat(this.dataForm.specialAreaJson[i].renew))) {
              this.$message.error('特殊地区续费金额不规范！')
              return
            }
            if (Number.parseFloat(this.dataForm.specialAreaJson[i].firstCharge) < 0 || !reg.test(this.dataForm.specialAreaJson[i].firstCharge) || !Number.isFinite(Number.parseFloat(this.dataForm.specialAreaJson[i].firstCharge))) {
              this.$message.error('特殊地区首费金额不规范！')
              return
            }
          }
        }
        if (this.dataForm.renewNum !== '' || this.dataForm.renew !== '') {
          this.dataForm.isRenew = 0
        } else {
          this.dataForm.isRenew = 1
        }
        if (this.dataForm.firstCharge !== '') {
          // let reg = /^(^[0-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,}$)$/
          let reg = /^[0-9]\d*$/
          if (Number.parseFloat(this.dataForm.firstCharge) < 0 || !reg.test(this.dataForm.firstCharge) || !Number.isFinite(Number.parseFloat(this.dataForm.firstCharge))) {
            this.$message.error('金额不规范！')
            return
          }
        } else {
          this.$message.error('请输入首费金额！')
          return
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // 如果只有省出现在数组中间就会导致回显问题，将无市的地区放在数组的后面
            let addArray = []
            let noCity = []
            if (this.dataForm.specialArea === '1') {
              for (let b = 0; b < this.dataForm.specialAreaJson.length; b++) {
                if (this.dataForm.specialAreaJson[b].cityId === '') {
                  noCity.push(this.dataForm.specialAreaJson[b])
                } else {
                  addArray.push(this.dataForm.specialAreaJson[b])
                }
              }
            }
            if (addArray.length > 0) {
              if (noCity.length > 0) {
                for (let c = 0; c < noCity.length; c++) {
                  addArray.push(noCity[c])
                }
              }
            } else {
              addArray = noCity
            }
            this.$http({
              url: this.$http.adornUrl(`/freight/${!this.dataForm.freightId ? 'addFreight' : 'modifyFreightById'}`),
              method: 'post',
              data: this.$http.adornData({
                'freightId': this.dataForm.freightId || undefined,
                'freightTitle': this.dataForm.freightTitle,
                'chargingType': this.dataForm.chargingType,
                'firstChargeNum': this.dataForm.firstChargeNum,
                'firstCharge': this.dataForm.firstCharge,
                'renew': this.dataForm.renew,
                'isRenew': this.dataForm.isRenew,
                'renewNum': this.dataForm.renewNum,
                'specialArea': this.dataForm.specialArea,
                'specialAreaJson': JSON.stringify(addArray),
                'remarks': this.dataForm.remarks
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 选择市
      provinceChanged (id) {
        this.old = false
        this.$http({
          url: this.$http.adornUrl('/member/area/querySubordinateList'),
          method: 'post',
          data: this.$http.adornData(id, false)
        }).then(({data}) => {
          this.dataForm.cityId = ''
          this.dataForm.cityList = data.data
        })
      },
      // 添加特殊地区
      addAddress () {
        // if (this.dataForm.provinceId !== '' && this.dataForm.cityId !== '') {
        if (this.dataForm.provinceId !== '') {
          if (this.dataForm.specialAreaJson.length > 0) {
            for (let b = 0; b < this.dataForm.specialAreaJson.length; b++) {
              if (this.dataForm.specialAreaJson[b].provinceId === this.dataForm.provinceId && this.dataForm.cityId === '') {
                this.$message.error('该省已添加到特殊地区！')
                return
              }
              // for (let c = 0; c < this.dataForm.cityList.length; c++) {
              //   if (this.dataForm.specialAreaJson[b].cityId === this.dataForm.cityList[c].id) {
              //     this.$message.error('该市已添加到特殊地区！')
              //     return
              //   }
              // }
              if (this.dataForm.cityId !== '') {
                if (this.dataForm.provinceId === this.dataForm.specialAreaJson[b].provinceId && this.dataForm.specialAreaJson[b].cityId === '') {
                  this.$message.error('该市已添加到特殊地区！')
                  return
                }
                if (this.dataForm.cityId === this.dataForm.specialAreaJson[b].cityId) {
                  this.$message.error('该市已添加到特殊地区！')
                  return
                }
              }
            }
          }
          this.dataForm.specialAreaJson.push({firstCharge: '0', firstChargeNum: '0',renewNum: '0','renew': '0',provinceId: this.dataForm.provinceId, cityId: this.dataForm.cityId})
        }
      },
      // 移除地区
      deleteHandle (id) {
        this.dataForm.specialAreaJson.splice(id, 1)
      },
    }
  }
</script>
